package com.ljx.qqpro.common.filter;

import cn.hutool.json.JSONUtil;
import com.ljx.qqpro.common.exception.MyException;
import com.ljx.qqpro.common.utils.JwtUtil;
import com.ljx.qqpro.common.utils.UserHolder;
import com.ljx.qqpro.entity.UserEntity;
import com.ljx.qqpro.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TokenInterceptor implements HandlerInterceptor {

    private final UserService userService;

    public TokenInterceptor(UserService userService) {
        this.userService = userService;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader("token");
        if(StringUtils.isEmpty(token)){
            return true;
        }

        // 检验token的合法性
        String username = JwtUtil.getUsername(token);
        if (StringUtils.isEmpty(username)) {
            throw new MyException("身份过期");
        }

        // TODO 查询权限

        UserEntity userInfo = userService.getUserInfo(username);
        UserHolder.saveUser(userInfo);

        return true;

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

}
